package com.yzt.zhuju.gift;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;

import androidx.annotation.NonNull;

import com.yzt.zhuju.R;
import com.yzt.zhuju.dialog.BaseDialog;
import com.yzt.zhuju.utils.GiftUtils;
import com.yzt.zhuju.utils.SvgaUtils;
import com.yzt.p_base.utils.DisplayUtils;
import com.opensource.svgaplayer.SVGACallback;
import com.opensource.svgaplayer.SVGADrawable;
import com.opensource.svgaplayer.SVGADynamicEntity;
import com.opensource.svgaplayer.SVGAImageView;
import com.opensource.svgaplayer.SVGAParser;
import com.opensource.svgaplayer.SVGAVideoEntity;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * author : bob
 * date   : 2022/12/5
 * desc   : 全局礼物动画加载
 */
public class GiftAnimShowDialog extends BaseDialog {

    private String gifGiftUrl;

    private String svgaImage;

    private String svgaConfig;

    private final MediaPlayer mediaPlayer = new MediaPlayer();

    private FrameLayout flowersLayout;

    @Override
    public int getGravity() {
        return Gravity.START;
    }

    @Override
    public int getLayoutRes() {
        return R.layout.dialog_anim_send_gift;
    }

    @Override
    public void bindView(View view) {
        String alphaVideoUrl;
        String soundFile;
        try {
            Bundle data = getArguments();
            gifGiftUrl = data.getString("gifGiftUrl");
            svgaImage = data.getString("svgaImage");
            alphaVideoUrl = data.getString("alphaVideoUrl");
            soundFile = data.getString("sound_file");
            svgaConfig = data.getString("svgaConfig");
        } catch (Exception e) {
            dismissDialog();
            return;
        }

        flowersLayout = view.findViewById(R.id.rlt_animation_layout);
        //特殊动画
       if (!TextUtils.isEmpty(svgaImage)) {
            showSvgaAnim(svgaImage);
        } else if (!TextUtils.isEmpty(gifGiftUrl)) {
            flowersLayout.setVisibility(View.VISIBLE);
            showGifAnim();
        } else {
            dismissDialog();
            return;
        }
        try {
            if (!TextUtils.isEmpty(soundFile)) {
                mediaPlayer.setDataSource(soundFile);
                //3 准备播放
                mediaPlayer.prepareAsync();
                mediaPlayer.setLooping(false);
                mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mediaPlayer) {
                        mediaPlayer.start();
                    }
                });
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        if (getDialog() != null && getDialog().getWindow() != null) {
            getDialog().getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            // 设置宽度为屏宽, 靠近屏幕底部。
            Window win = getDialog().getWindow();
            // 一定要设置Background，如果不设置，window属性设置无效
            win.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

            WindowManager.LayoutParams params = win.getAttributes();
            params.dimAmount = 0;
            params.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
            params.gravity = Gravity.START;
            // 使用ViewGroup.LayoutParams，以便Dialog 宽度充满整个屏幕
            params.width = ViewGroup.LayoutParams.MATCH_PARENT;
            params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
            win.setAttributes(params);
        }
    }

    /**
     * 加载动画
     */
    private void showSvgaAnim(String imgRes) {
        flowersLayout.setVisibility(View.VISIBLE);
        flowersLayout.addView(initSpecialAnimView(imgRes));
    }

    /**
     * gif全屏动画
     */
    private void showGifAnim() {
        if (getActivity().isDestroyed() || getActivity().isFinishing()) {
            return;
        }
        final ImageView ivGifGiftAnim = new ImageView(getActivity());
        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        int viewWidth = DisplayUtils.getDisplayPxWidth() - DisplayUtils.dp2px(40);
        layoutParams.width = viewWidth;
        layoutParams.height = (int) (viewWidth / 750f * 1300);
        GiftUtils.showGiftAnimation(gifGiftUrl, mActivity, ivGifGiftAnim, new GiftUtils.OnGiftStatus() {
            @Override
            public void onStart() {

            }

            @Override
            public void onEnd() {
                dismissDialog();
            }
        });
        flowersLayout.addView(ivGifGiftAnim, layoutParams);
    }

    /**
     * 全屏特殊动画
     */
    private SVGAImageView initSpecialAnimView(String animPath) {
        final SVGAImageView svgaImageView = new SVGAImageView(getActivity());
        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(DisplayUtils.getDisplayPxWidth(),
                DisplayUtils.getDisplayPxHeight());
        svgaImageView.setLayoutParams(layoutParams);
        svgaImageView.setLoops(1);
        svgaImageView.setClearsAfterStop(true);
        svgaImageView.setCallback(new SVGACallback() {
            @Override
            public void onStep(int i, double v) {
            }

            @Override
            public void onRepeat() {
            }

            @Override
            public void onFinished() {
                dismissDialog();
            }

            @Override
            public void onPause() {
            }
        });

        if (TextUtils.isEmpty(svgaConfig)) {
            SvgaUtils.loadSvga(svgaImageView, svgaImage);
        } else {
            SVGAParser svgaParser = new SVGAParser(getActivity());
            try {
                if (animPath.startsWith("http")) {
                    URL url = new URL(animPath);
                    svgaParser.parse(url, getParseCompletion(svgaImageView));
                } else {
                    svgaParser.parse(animPath, getParseCompletion(svgaImageView));
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
        }
        return svgaImageView;
    }

    @NonNull
    private SVGAParser.ParseCompletion getParseCompletion(SVGAImageView svgaImageView) {
        return new SVGAParser.ParseCompletion() {
            @Override
            public void onComplete(SVGAVideoEntity svgaVideoEntity) {
                SVGADynamicEntity svgaDynamicEntity = SvgaUtils.requestDynamicItem(svgaConfig);
                if (null != svgaDynamicEntity) {
                    SVGADrawable drawable = new SVGADrawable(svgaVideoEntity, svgaDynamicEntity);
                    svgaImageView.setImageDrawable(drawable);
                } else {
                    svgaImageView.setVideoItem(svgaVideoEntity);
                }
                svgaImageView.startAnimation();
            }

            @Override
            public void onError() {

            }
        };
    }

    private void dismissDialog() {
        try {
            if (getActivity().isDestroyed() || getActivity().isFinishing()) {
                return;
            }
            if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
                mediaPlayer.release();
            }
            //设置后，可重新生成GiftAnimDialogFragment
            setCancelable(true);
            dismissAllowingStateLoss();
        } catch (Exception ignored) {

        }
    }
}

